# coding=utf-8

import pymel.core as pm
from ..control import Control


def fk(prefix="fk"):
    u"""
    选择一个骨骼链与执行
    用来生成一串FK。
    :param prefix: 前缀
    :return:
    """
    selected = pm.selected(type="joint")
    if not len(selected) == 1:
        return pm.warning("please selected a joint")
    fits = selected + list(reversed(pm.listRelatives(selected[0], ad=1)))
    radius = (fits[0].getTranslation(space="world")-fits[1].getTranslation(space="world")).length()/2
    iks = []
    group = pm.group(em=1, n=prefix+"Group")
    group.setMatrix(fits[0].getMatrix(ws=1), ws=1)
    fk_con = group
    joint = group
    fk_node = pm.createNode("MYFk")
    direction = (pm.datatypes.Point(fits[1].getTranslation(space="world"))*fits[0].getMatrix(ws=1))[0]>0
    fk_node.direction.set(direction)
    for i, fit in enumerate(fits):
        _prefix = prefix + "%02d" % (i+1)
        fk_con = Control(n=_prefix+"FkControl", s="cuboid", r=radius, c=13, p=fk_con, l=["v", "s"])
        fk_con.offsetParentMatrix.set(fit.getMatrix(ws=1)*fk_con.getMatrix(ws=1).inverse())
        ik_con = Control(n=_prefix+"IkControl", s="star", r=radius, c=13, p=fk_con, l=["v", "sx"])
        iks.append(ik_con)
        joint = pm.joint(joint, n=_prefix+"Joint")
        joint.radius.set(radius * 0.1)
        if i == 0:
            joint.parentInverseMatrix[0].connect(fk_node.jpi)
            ik_con.parentInverseMatrix[0].connect(fk_node.cpi)
        ik_con.worldMatrix[0].connect(fk_node.control[i])
        fk_node.joint[i].rotate.connect(joint.rotate)
        fk_node.joint[i].translate.connect(joint.translate)
        ik_con.s.connect(joint.s)
